import { Component, OnInit, Host, ViewChild } from '@angular/core';
import { AppComponent } from '../../../app.component';
import { TableOptions } from '../../../shared/components/table/models/tableOptions.model';
import { PaginationPositionDisplayEnum, TableComponent } from '../../../shared/components/table/table.component';
import { ColumnOptions, ColumnType } from '../../../shared/components/table/models/columnOptions.model';
import { InsightsService } from './insights.service';
import { Page } from '../../../shared/components/table/models/pagination.model';
import { TableButton, ButtonType } from '../../../shared/components/table/models/tableButton.model';
import { TableRouterLink } from '../../../shared/components/table/models/tableRouterLink.model';
import { NameModel } from './model/insightsNames.model';
import swal, { SweetAlertOptions } from 'sweetalert2';
import { ToasterService } from 'angular2-toaster';
import { InsightStatus } from './model/insights.model';

@Component({
  templateUrl: './insights.component.html'
})
export class InsightsComponent implements OnInit {
  private options: TableOptions;
  public insights: any[];
  public selectedInsights: any[] = [];
  public count: number;

  public selectedTopic: string;
  public topics: NameModel[];
  public selectedSector: string;
  public sectors: NameModel[];

  public paginationPosition = PaginationPositionDisplayEnum.Down;
  public columns: ColumnOptions[] = [
    new ColumnOptions('selected', 'Select', 'col-md-1', false, ColumnType.Buttons),
    new ColumnOptions('title', 'Publication Title', 'col-md-4', true, ColumnType.Link),
    new ColumnOptions('publishedDate', 'Date Added', 'col-md-2', false, ColumnType.DateTime),
    new ColumnOptions('addedBy', 'Added by', 'col-md-2', false, ColumnType.Label),
    new ColumnOptions('status', 'Status', 'col-md-1', false, ColumnType.Label),
    new ColumnOptions('unpublishedDate', 'Unpublished Date', 'col-md-2', false, ColumnType.DateTime)
  ];
  public filter: any = { name: '' };

  @ViewChild('insightsTable') insightsTable: TableComponent;

  constructor(@Host() private rootComponent: AppComponent,
    private insightsService: InsightsService,
    private toasterService: ToasterService) { }

  ngOnInit() {
    this.options = new TableOptions('title');
    this.options.filter = this.filter;
    this.getInsights();
    this.insightsService.getInsightsNames().subscribe(data => {
      this.topics = data.topicNames;
      this.sectors = data.sectorNames;
    });
  }

  private getInsights(listOnly: boolean = false) {
    if (listOnly == false) {
      if (this.options.pageOptions.skip > 0) this.insightsTable.pageChanged(new Page(0, 20));
      this.insightsService.getInsightsCount(this.options.filter.name, this.selectedTopic, this.selectedSector).subscribe(data => {
        this.count = data;
      });
    }

    this.insightsService.getInsightsList(this.options.filter.name, this.selectedTopic, this.selectedSector, this.options.pageOptions.skip, this.options.pageOptions.take).subscribe(data => {
      this.insights = data.map(insight => {
        return {
          selected: [new TableButton('selected', { id: insight.id, selected: this.selectedInsights.indexOf(insight.id) > -1, status: insight.state }, true, ButtonType.CheckBox)],
          title: new TableRouterLink(insight.title, true, ['true', insight.id]),
          publishedDate: new Date(insight.datePublished),
          addedBy: insight.addedByUserName,
          status: InsightStatus[insight.state],
          unpublishedDate: new Date(insight.dateUnPublished)
        }
      });
      this.rootComponent.finishLoading();
    });
  }

  public tableOptionsChanged(tableOptions: TableOptions) {
    this.options = tableOptions;
    this.getInsights(tableOptions.pageOptions.listOnly);
  }

  public onInsightSelectionChanged(insight: any) {    
    if (insight.selected == false)      
      this.selectedInsights.push({ id: insight.id, status: insight.status });
    else
      this.selectedInsights.splice(this.selectedInsights.findIndex(x => x.id == insight.id), 1);
  }

  public deleteInsights() {
    const swalOptions: SweetAlertOptions = {
      buttonsStyling: false,
      customClass: 'modal-content',
      showCancelButton: true,
      title: 'Delete Events',
      text: 'A number of ' + this.selectedInsights.length + ' insights will be removed. Are you sure that you want to continue?',
      confirmButtonClass: 'btn btn-primary',
      confirmButtonText: 'Delete',
      cancelButtonClass: 'btn btn btn-outline-dark-grey'
    };
    swal(swalOptions).then(result => {
      if (result && result.value) {
        this.insightsService.deleteInsights(this.selectedInsights.map(function (o) { return { resourceid: o.id, verb: 'DELETE' } })).subscribe(_ => {
          let ids: string[] = this.insights.map(x => x.selected[0].actionOptions.id);
          for (var i = 0; i < ids.length; i++) {
            if (this.selectedInsights.findIndex(x => x.id == ids[i]) > -1) {
              this.insights.splice(i, 1);
              ids.splice(i, 1);
              i--;
            }
          }
          this.insightsTable.updateSource(this.insights);
          this.selectedInsights = [];
          this.toasterService.pop('success', 'Success', 'Insights deleted successfull.');
        });
      }
    });
  }

  public publishInsights() {
    //check selected
    if (this.selectedInsights.findIndex(x => x.status != InsightStatus.Draft) > -1)
      this.toasterService.pop('warning', 'Warning', 'Only items in status Draft can be published, please check your selection and try again.');
    else {
      const swalOptions: SweetAlertOptions = {
        buttonsStyling: false,
        customClass: 'modal-content',
        showCancelButton: true,
        title: 'Delete News',
        text: 'A number of ' + this.selectedInsights.length + ' insihgts will be published. Are you sure that you want to continue?',
        confirmButtonClass: 'btn btn-primary',
        confirmButtonText: 'Publish',
        cancelButtonClass: 'btn btn btn-outline-dark-grey'
      };
      swal(swalOptions).then(result => {
        if (result && result.value) {
          this.insightsService.publishInsights(this.selectedInsights.map(function (o) { return { resourceid: o.id, verb: 'PATCH', newState: InsightStatus.Published } })).subscribe(_ => {
            this.insights.filter(x => this.selectedInsights.findIndex(y => y.id == x.selected[0].actionOptions.id) > -1).forEach(x => {
              x.status = InsightStatus[InsightStatus.Published];
              x.selected[0].actionOptions.selected = false;
            });
            this.insightsTable.updateSource(this.insights);
            this.selectedInsights = [];
            this.toasterService.pop('success', 'Success', 'Insights published successfull.');
          });
        }
      });
    }
  }
}
